# encoding: utf-8
# Author    : limusen
# Datetime  : 2023/8/14 10:32
# File      : Logins.py
# explain   : 文件说明


import json
import requests
from common.base import Bases
from common.read_yaml import revise_yml_data
from common.read_yaml import get_yml_data
from common.log import logger


class Action:

    def __init__(self):
        self.base = Bases()
        self.url = get_yml_data('all_param', 'urls')

    def login(self, host):
        """
        登录接口 获取token 拼接参数提供创建连机器接口使用
        :param host: 域名
        :return: token信息
        """
        try:
            if host.endswith('198'):
                response = self.base.Post(self.url['login_url_198'], json=json.loads(self.base.GetCode(host)))
                if response.json()['code'] != 400 and response.json().get('data')['Authorization'] != None:
                    autho = response.json()['data']['Authorization']
                    revise_yml_data('sync','all_param', 'headers', 'Authorization', autho)
                    logger.info("当前替换配置的 Authorization ： %s " % autho)
                    return response.json()
            elif host.endswith('127'):
                response = self.base.Post(self.url['login_url_127'], json=json.loads(self.base.GetCode(host)))
                if response.json()['code'] != 400 and response.json().get('data')['Authorization'] != None:
                    autho = response.json()['data']['Authorization']
                    revise_yml_data('sync','all_param', 'headers', 'Authorization', autho)
                    logger.info("当前替换配置的 Authorization ： %s " % autho)
                    return response.json()
            else:
                return '当前域名暂未做配置,请重新输入...'
        except TypeError as e:
            logger.error('正常逻辑获取验证码失败，报错后重新请求获取验证码并重试.....')
            if host.endswith('198'):
                response = self.base.Post(self.url['login_url_198'], json=json.loads(self.base.GetCode(host)))
                if response.json()['code'] != 400 and response.json().get('data')['Authorization'] != None:
                    autho = response.json()['data']['Authorization']
                    revise_yml_data('sync','all_param', 'headers', 'Authorization', autho)
                    logger.error("TypeError -- 替换 Authorization ： %s " % autho)
                    return response.json()
            elif host.endswith('127'):
                response = self.base.Post(self.url['login_url_127'], json=json.loads(self.base.GetCode(host)))
                if response.json()['code'] != 400 and response.json().get('data')['Authorization'] != None:
                    autho = response.json()['data']['Authorization']
                    revise_yml_data('sync','all_param', 'headers', 'Authorization', autho)
                    logger.error("TypeError -- 替换 Authorization ： %s " % autho)
                    return response.json()


if __name__ == '__main__':
    Action().login('198')
